<?php

namespace App\Admin\Forms;

use App\Jobs\JobQueue;
use App\Models\ProjectExportRecordsDetail;
use App\Models\User;
use App\Notifications\ToPayNotify;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ToPayBatchToolsForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public $elementId = 'to-pay';

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // 获取选中的导出记录
        $recordDetailList = ProjectExportRecordsDetail::whereIn('id', explode(',', $input['id']))->get();
        // dd($recordDetailList);
        // 获取导出记录主表id
        $records_id = $recordDetailList[0]->records_id;
        // 把操作记录取出来
        // $lastLogs = $recordDetailList->pluck('audit_log')->toArray();
        // 统计导出记录条数,准备设置主表的成功失败条数
        $setCount = count($recordDetailList);

        // 劳务审核状态
        if ($input['pay_status'] == '2') {
            $audit_fee = '1';
            \App\Models\ProjectExportRecord::where('id', $records_id)
                ->increment('pay_success', $setCount);
        } elseif ($input['pay_status'] == '-1') {
            $audit_fee = '-1';
            \App\Models\ProjectExportRecord::where('id', $records_id)
                ->increment('pay_fail', $setCount);
        }
        // 当前审核记录
        $log = [
            [
                'audit_global_status' => 2,
                'audit_user' => Admin::user()->name,
                'audit_time' => date('Y-m-d H:i:s'),
                'pay_status' => $input['pay_status'],
                'audit_remark' => $input['audit_remark'] ?? '',
                'audit_fee' => $audit_fee,
            ],
        ];

        try {

            foreach ($recordDetailList as $key => $val) {
                $lastLog = empty(json_decode($val['audit_log'], true)) ? [] : json_decode($val['audit_log'], true);

                \App\Models\ProjectAgreement::where('id', $val['project_agreement_id'])
                    ->update([
                        'audit_fee' => $audit_fee, // 劳务审核
                        'status' => $audit_fee,
                        'audit_remark' => ($audit_fee == 1 ? '' : $input['audit_remark']),
                        'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
                        'pay_status' => $input['pay_status'],
                        'receipt_form' => $input['receipt_form'] ? $input['receipt_form'] : '',
                        'paymentd_at' =>  $input['paymentd_at'] ? $input['paymentd_at'] : null,
                    ]);


                \App\Models\ProjectExportRecordsDetail::where('id', $val['id'])
                    ->update([
                        'audit_fee' => $audit_fee, // 劳务审核
                        'status' => $audit_fee,
                        'audit_remark' => ($audit_fee == 1 ? '' : $input['audit_remark']),
                        'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
                        'pay_status' => $input['pay_status'],
                        'receipt_form' => $input['receipt_form'] ? $input['receipt_form'] : '',
                        'paymentd_at' =>  $input['paymentd_at'] ? $input['paymentd_at'] : null,
                    ]);

                // Log::info('------ 发送通知 BatchToPay ------');
                // $user = User::find($val['user_id']);
                // \Illuminate\Support\Facades\Notification::send(
                //     $user,
                //     (new ToPayNotify($input, $user))->onQueue(JobQueue::BATCH_PAY_NOTIFY)
                // );
            }

            return $this
                ->response()
                ->success('操作成功')
                ->refresh();
        } catch (\Exception $e) {
            Log::info('----------catch----------', ['exception' => json_encode($e)]);
            return $this
                ->response()
                ->error('操作失败')
                ->refresh();
        }
    }


    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('pay_status', '审核状态')->options(['2' => '审核通过', '-1' => '审核驳回'])->when(
            '-1',
            function (Form $form) {
                $form->textarea('audit_remark', '审核意见');
            }
        )->when(
            '2',
            function (Form $form) {
                $form->multipleImage('receipt_form', '上传回执单')
                    ->accept('jpg,png,gif,jpeg')
                    ->help('只允许上传jpg、png、gif、jpeg格式的图片文件')
                    ->saveFullUrl()
                    ->autoUpload()
                    ->rules('required_if:status,1', ['required_if' => '请填写完整该项'])
                    ->saving(function ($value) {
                        return implode(',', httpToHttps($value));
                    });
                $form->datetime('paymentd_at', '支付时间');
            }
        )->required();
        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'reset-password-id');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function
    default()
    {

        return [];
    }
}
